#!/usr/bin/env python

#    Copyright 2011,2012 Erik Persson
#
#    This file is part of the cell-sync-usrp project.
#
#    cell-sync-usrp is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    cell-sync-usrp is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with cell-sync-usrp.  If not, see <http://www.gnu.org/licenses/>.


import struct
import sys
sys.path.append( "../convolution" )

import convolution
import scramblingcodegen


def main():
    conv = convolution.Convolution(9,2,[[0,2,3,4,8],[0,1,2,3,5,7,8]])
    
    simpleSeq = [1,1,0,0,1,1,0,0,1,1]
    
    longSeq = []
    for i in range(0,26):
        longSeq.extend(simpleSeq);
    
    longSeq.extend([0,0,0,0,0,0,0,0,0,0])
    
    print "Length longSeq: " + str(len(longSeq))
    
    coded = conv.insertSeq(longSeq)
    print coded
    print "Length coded: " + str(len(coded))
    symbols = []
    for c in coded:
        if (c[0] == 1):
            r = -1.0
        else:
            r = 1.0
        if (c[1] == 1):
            i = -1.0
        else:
            i = 1.0
            
        symbols.append((r,i))
        
    chips = []
    for i in range(0,270):
        for j in range (0,256):
            if (j < 128):
                d1 = symbols[i]
            else:
                d1 = (-symbols[i][0], -symbols[i][1])
            chips.append(d1)
            
    #512+splitChips1+512+splitChips2 = two frames = one BCCH TTI
    
        
        
    
    f = open("BCCHseq","wb")
    
    pos = 0

    for i in range(0,30):
        for times in range(0,256):
            chips.insert(pos, (0.0,0.0))
        pos+=2560
    
    
    s = 16*8*12+16*7
    complexList = []
    for i in range(0, 38400*2):        
        real = scramblingcodegen.getZ(s,i%38400)
        imag = scramblingcodegen.getZ(s,(i%38400)+131072)
        if (real==0):
            real=1
        else: 
            real = -1
        if (imag==0):
            imag = 1
        else:
            imag = -1
        one = complex(chips[i][0],chips[i][1])
        two = complex(real,imag)
        
        data = one*two#(chips[i][0] + chips[i][1]*j) * (real + imag)
        complexList.append( data)
        print data, chips[i][0], real, chips[i][1], imag

    
    for c in complexList:
        f.write(struct.pack("ff",c.real,c.imag))
        f.write(struct.pack("ff",c.real,c.imag))
    
    f.close()
    
    print "chip length: " + str(len(chips))
    
    
if __name__ == '__main__':
    main()
    
